package de.fhkl.ut.btread01;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class Android_BT_Read_01Activity extends Activity {
    // Debugging
    private static final String TAG = "BluetoothChat";
    private static final boolean D = true;
    
    // Layout Views
    private ListView mConversationView;

    // Array adapter for the conversation thread
    private ArrayAdapter<String> mConversationArrayAdapter = null;
    
    // String buffer for outgoing messages
    private StringBuffer mOutStringBuffer;    
    
    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 2;
    private static final int REQUEST_ENABLE_BT = 3;
     
    // Local Bluetooth adapter
    private BluetoothAdapter mBluetoothAdapter = null;

    // Name of the connected device
    private String mConnectedDeviceName = null;
    
    // Member object for the chat services
    private BluetoothReaderWriterService mEkgService = null;
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        Intent serverIntent = null;
        
        super.onCreate(savedInstanceState);
        if(D) Log.e(TAG, "+++ ON CREATE +++");
        
        setContentView(R.layout.main);

        // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        
        // If BT is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBluetoothAdapter.isEnabled()) {
            Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        } else {
            // Launch the DeviceListActivity to see devices and do scan
            serverIntent = new Intent(this, DeviceListActivity.class);
            startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);
        }
    } 

    @Override
    public void onStart() {
        super.onStart();
        if(D) Log.e(TAG, "++ ON START ++");
    }
    

    @Override
    public synchronized void onResume() {

        super.onResume();
        if(D) Log.e(TAG, "+ ON RESUME +");

        // Performing this check in onResume() covers the case in which BT was
        // not enabled during onStart(), so we were paused to enable it...
        // onResume() will be called when ACTION_REQUEST_ENABLE activity returns.
        if (mEkgService != null) {
            // Only if the state is STATE_NONE, do we know that we haven't started already
            if (mEkgService.getState() == BluetoothReaderWriterService.STATE_NONE) {
                //Start the Bluetooth chat services

            }
        }
    }
    
    @Override
    public synchronized void onPause() {
        super.onPause();
        if(D) Log.e(TAG, "- ON PAUSE -");
    }

    @Override
    public void onStop() {
        super.onStop();
        if(D) Log.e(TAG, "-- ON STOP --");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // Stop the Bluetooth chat services
        if (mEkgService != null) mEkgService.stop();
        if(D) Log.e(TAG, "--- ON DESTROY ---");
    }
    
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Intent serverIntent = null;
    	if(D) Log.d(TAG, "onActivityResult " + resultCode);
        
        switch (requestCode) {
        case REQUEST_CONNECT_DEVICE:
            // When DeviceListActivity returns with a device to connect
            if (resultCode == Activity.RESULT_OK) {
            	// Bluetooth is now enabled, so set up a chat session
            	setup();
                connectDevice(data);
            }
            break;
            
        case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Launch the DeviceListActivity to see devices and do scan
                serverIntent = new Intent(this, DeviceListActivity.class);
                startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE);            
            } else {
                // User did not enable Bluetooth or an error occurred
                Log.d(TAG, "BT not enabled");
                Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
    
    private void setup() {
        Log.d(TAG, "setup()");

        // Initialize the array adapter for the conversation thread
        mConversationArrayAdapter = new ArrayAdapter<String>(this, R.layout.message);
        mConversationView = (ListView) findViewById(R.id.in);
        mConversationView.setAdapter(mConversationArrayAdapter);

        // Initialize the BluetoothChatService to perform bluetooth connections
        mEkgService = new BluetoothReaderWriterService(this, mHandler);

        // Initialize the buffer for outgoing messages
        mOutStringBuffer = new StringBuffer("");
    }
    
    private void connectDevice(Intent data) {
        Log.d(TAG, "connectDevice()");
        
        // Get the device MAC address
        String address = data.getExtras().getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
        // Get the BluetoothDevice object
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
        // Attempt to connect to the device
        mEkgService.connect(device);
    }
    
    // The Handler that gets information back from the BluetoothChatService
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            case BluetoothReaderWriterService.MESSAGE_STATE_CHANGE:
                if(D) Log.i(TAG, "MESSAGE_STATE_CHANGE: " + msg.arg1);
                switch (msg.arg1) {
                case BluetoothReaderWriterService.STATE_CONNECTED:
                    Toast.makeText(getApplicationContext(), R.string.title_connected_to +
                                   mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                    mConversationArrayAdapter.clear();
                    break;
                case BluetoothReaderWriterService.STATE_CONNECTING:
                    Toast.makeText(getApplicationContext(), R.string.title_connecting, Toast.LENGTH_SHORT).show();
                    break;
                case BluetoothReaderWriterService.STATE_NONE:
                    Toast.makeText(getApplicationContext(), R.string.title_not_connected, Toast.LENGTH_SHORT).show();
                    break;
                }
                break;
            case BluetoothReaderWriterService.MESSAGE_WRITE:
                byte[] writeBuf = (byte[]) msg.obj;
                // construct a string from the buffer
                String writeMessage = new String(writeBuf);
                mConversationArrayAdapter.add("Me:  " + writeMessage);
                break;
            case BluetoothReaderWriterService.MESSAGE_READ:
                byte[] readBuf = (byte[]) msg.obj;
                // construct a string from the valid bytes in the buffer
                String readMessage = new String(mConnectedDeviceName+": ");
                for (int i=0; i<msg.arg1; i+=2) {
                	String s1 = new String("00000000"+Integer.toBinaryString( 0xFF & (int) readBuf[i] ));  
                    readMessage = readMessage.concat(s1.substring(s1.length()-8, s1.length())).concat(" - ");
                    if (i+1 < msg.arg1) {
                    	String s2 = new String("00000000"+Integer.toBinaryString( 0xFF & (int) readBuf[i+1] ));
                        readMessage = readMessage.concat(s2.substring(s2.length()-8, s2.length())).concat("\n");
                    }
                }

                mConversationArrayAdapter.add(readMessage);
                break;
            case BluetoothReaderWriterService.MESSAGE_DEVICE_NAME:
                // save the connected device's name
                mConnectedDeviceName = msg.getData().getString(BluetoothReaderWriterService.STR_DEVICE_NAME);
                Toast.makeText(getApplicationContext(), R.string.title_device_name + 
                		       mConnectedDeviceName, Toast.LENGTH_SHORT).show();
                break;
            case BluetoothReaderWriterService.MESSAGE_TOAST:
                Toast.makeText(getApplicationContext(), msg.getData().getString(BluetoothReaderWriterService.STR_TOAST),
                               Toast.LENGTH_SHORT).show();
                break;
            }
        }
    };
}